import backtrader as bt
import backtrader.indicators as btind
import talib

from state_inds.check_state import Check_bottom, BBand_converge, VolBurst, Result_ind, OBV


class Screener_Bottom(bt.Analyzer):
# class Screener_Bottom(bt.Strategy):
    '''
    需求：
    底部
    下降趋势结束
    布林带收缩
    放量
    =========
    使用：
    需要获取本指标的最小预热周期，作为输入数据的历史截取依据
    '''
    params = (('period',20), ('devfactor',2),)

    def __init__(self):
        self.bband = bt.indicators.BollingerBands(self.data.close,
                period=self.p.period, devfactor=self.p.devfactor)
        self.is_bottom = Check_bottom(lookback=100, percentage=0.2)
        # print(self.is_bottom._minperiod)
        self.bband_converge = BBand_converge(period=20, devfactor=2, converge_num=5, only_decline=True,slope=-0.1)
        # print(self.bband_converge._minperiod)
        self.rv_ind=VolBurst(period=20, threshold=3)

        # self.rv_signal=rv_ind.lines.rv_signal
        # self.rv=rv_ind.lines.rv
        self.obv=OBV()
        self.my_ind = Result_ind(strategy=self)

        
        self.conv_newest=0
        self.burst_newest=0
        self.new_platform=False
        self.condition= False
        self.rets['state']='none'
    

    def next(self):
        # 如果成员变量中有任何值等于 NaN，则什么都不做，直接pass
        # if any(map(lambda x: x != x, [self.is_bottom[0], self.bband_converge[0]])):
        if any(map(lambda x: x != x,
                   [self.is_bottom, self.bband_converge, self.obv,self.rv_ind.rv_signal])):
            return
        if self.condition:
            self.condition=False

        if self.is_bottom and self.bband_converge:
            self.conv_newest = len(self)
            self.conv_price= self.data.close
            self.rets['conv date']=self.data.datetime.date()
            self.rets['state']='converge'

        if self.rv_ind.rv_signal and self.conv_newest and len(self)-self.conv_newest<15:
            self.rets['vol date']=self.data.datetime.date()
            self.first_burst=True
            self.rets['state']='burst'
            self.condition=True
            
        



    # def stop(self):
    #     if self.stage2 and len(self)-self.stage2<5:
    #         self.rets['chance occur']=True
    #     else:
    #         self.rets['chance occur']=False


            
        

                
                
class Screener2(bt.Analyzer):
    '''
    1. obv 形成平台（保证安全）
    2. 价格也形成平台
    （可以用布林带收缩带来概率加成，说明时间将近
     可以用找圆弧，方法待定
     一旦站上新平台，可以用动态指标，将统计起点设为平台的起点
     ）
    '''
    params = (('period',20), ('devfactor',2),)
    def start(self):
        pass
    def next(self):
        pass
    def stop(self):
        self.rets['over'] = list()


class Screener3(bt.Analyzer):
    params = (('period', 20), ('devfactor', 2),)
    
    def start(self):
        pass
    
    def next(self):
        pass
    
    def stop(self):
        self.rets['over'] = list()




